package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client3 {
    private Socket socket;

    public Client3() {
        try {
            System.out.println("正在连接服务器");
            socket = new Socket("localhost", 8088);
            //  socket=new Socket("176.125.111.235",8088);

            //socket=new Socket("176.125.111.251",8088);
            // socket=new Socket("176.125.111.237",8189);
            System.out.println("与服务器连接成功");
            System.out.println("型芯不");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    void start() {
        try {
            //ServerHandler匿名内部类提取出外面可见类的写法
            Thread ne = new Thread(new ServerHandler());
            ne.start();

            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);


            Scanner sc = new Scanner(System.in);
            System.out.println("请输入您想发送的消息,按回车发送");
            while (true) {
                String line = sc.next();
                if ("exit".equals(line))
                    break;
                pw.println(line);
            }
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                System.out.println("下线...");
                //socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        Client3 client = new Client3();
        client.start();

    }

    private class ServerHandler implements Runnable {
        @Override
        public void run() {
            try {
                InputStream is = null;
                is = socket.getInputStream();//服务端的公告输入流
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println("服务端返回:" + socket.getInetAddress().getHostAddress() + ":" + line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
